import axios from "axios";
import {ElMessage} from "element-plus";
import useStore from "../store/modules/users.ts";
import router from "../router";

let request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 5000
});

request.interceptors.request.use((config) => {
    const store = useStore();
    if (store.token) {
        config.headers.token = store.token
    }
    return config;
});

request.interceptors.response.use((response) => {
    return response.data;
}, (error) => {
    let message = '';
    let status = error.response?.status;

    switch (status) {
        case 401:
            message = "未认证";
            // token失效，清除用户信息并跳转到登录页
            const store = useStore();
            store.userLogout().then(() => {
                router.push("/login");
            });
            break;
        case 403:
            message = "无权限";
            break;
        case 404:
            message = "找不到";
            break;
        case 500:
            message = "服务器崩了";
            break;
        default:
            message = "网络问题";
            break;
    }

    ElMessage({
        type: "error",
        message: message
    });

    return Promise.reject(error);
});

export default request;
